﻿using System;
using System.Data;
using System.Configuration;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using GlynnTucker.Cache;
using TWS.Controller.Paging;
using System.Text.RegularExpressions;
using System.Collections;

/// <summary>
/// Summary description for BaseAdminPage
/// </summary>
public class BaseAdminPage : System.Web.UI.Page 
{
	public BaseAdminPage()
	{
		//
		// TODO: Add constructor logic here
		//
       
	}
    private int m_totalRecord = 0;

    public int TotalRecord {
        get {
            return m_totalRecord;
        }
        set {
            m_totalRecord = value;
        }
    }

    public int PagingSize {
        get {
            int result = 0;
            string val = ConfigurationManager.AppSettings["PagingSize"];

            result = Convert.ToInt32(val);
            return result;
        }
    }

    private string m_pageString = string.Empty;

    public string PageString {
        set {
            m_pageString = value;
        }
        get {
            return m_pageString;
        }
    }

    public string ImagePath {
        get {
            string result = "";
            object tmp = GetFromCache("ImagesFolder");
            if (tmp != null) {
                result = (string)tmp;
            } else {
                result = ConfigurationManager.AppSettings["ImagesFolder"];
                AddToCache("ImagesFolder", result);
            }
            return result;
        }
    }
    public static void FindContainedNamingContainers(Control c, bool bRecursive, IList list) {
        IEnumerator enumerator = null;
        try {
            enumerator = c.Controls.GetEnumerator();
            while (enumerator.MoveNext()) {
                Control child = (Control)enumerator.Current;
                if (child is INamingContainer) {
                    list.Add(child);
                }
                if (bRecursive) {
                    FindContainedNamingContainers(child, true, list);
                }
            }
        } finally {
            if (enumerator is IDisposable) {
                (enumerator as IDisposable).Dispose();
            }
        }
    }

    public static Control FindControlRecursively(Control parent, string id) {
        IEnumerator enumerator = null;
        if (parent != null && id != null) {
        }
        if (id.Length == 0) {
            throw new ArgumentNullException();
        }
        Control c = parent.FindControl(id);
        if (c != null) {
            return c;
        }
        ArrayList namingContainers = new ArrayList();
        FindContainedNamingContainers(parent, true, namingContainers);
        try {
            enumerator = namingContainers.GetEnumerator();
            while (enumerator.MoveNext()) {
                c = ((Control)enumerator.Current).FindControl(id);
                if (c != null) {
                    return c;
                }
            }
        } finally {
            if (enumerator is IDisposable) {
                (enumerator as IDisposable).Dispose();
            }
        }
        return null;
    }

    public void RedirectPage(string page, bool remeberLastPage)
    {
        if (remeberLastPage)
        {
            string prevPage = Request.Url.AbsolutePath;
            int i = prevPage.IndexOf(".aspx");
            if (i > 0)
            {
                Session["LastVisitedPage"] = Request.Url.PathAndQuery;
            }
            else
            {
                Session["LastVisitedPage"] = Request.Url.AbsolutePath;
            }
        }
        Response.Redirect(page);

    }
    public void RedirectPageCallBack(string page, bool remeberLastPage) {
        if (remeberLastPage) {
            Session["LastVisitedPage"] = Request.Url.PathAndQuery;
        }

    }

    public void RedirectLastVisitedPage() {
        string lastPage = (string)Session["LastVisitedPage"];

        if (lastPage != string.Empty && lastPage != null) {
            Response.Redirect(lastPage);
        } else {
            Response.Redirect(UIPage.AppPath+"/TrangChu.aspx");//TODO: read from config
        }

    }



    public Paging getPagingObject(int totalRecord, int currentPage) {
        Paging page = new Paging(totalRecord);

        page.CurrentPage = currentPage;
        page.PerPage = PagingSize;
        page.Param = "pg";
        page.CurrentMode = Mode.None;
        page.QueryString = Regex.Replace(this.Request.RawUrl, @"(&pg|\?pg)=[\d]+", string.Empty, RegexOptions.IgnoreCase);
        page.ShowLast = true;
        page.ShowFirst = true;
        page.LinksBefore = 10;
        page.LinksAfter = 10;

        return page;
    }
    public Paging getPagingObject(int totalRecord, int currentPage,int pagesize)
    {
        Paging page = new Paging(totalRecord);

        page.CurrentPage = currentPage;
        page.PerPage = pagesize;
        page.Param = "pg";
        page.CurrentMode = Mode.None;
        page.QueryString = Regex.Replace(this.Request.RawUrl, @"(&pg|\?pg)=[\d]+", string.Empty, RegexOptions.IgnoreCase);
        page.ShowLast = true;
        page.ShowFirst = true;
        page.LinksBefore = 10;
        page.LinksAfter = 10;

        return page;
    }
    #region Cache controler
    /// <summary>
    /// Add or update cache
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    private void AddToCache(string key, object value) {
        SimpleMemoryCache cache;
        if (Application["SystemCache"] == null) {
            cache = new SimpleMemoryCache();
            Application["SystemCache"] = cache;
        } else {
            cache = (SimpleMemoryCache)Application["SystemCache"];
        }

        if (!cache.Contains(key)) {
            cache.Add(key, value, DateTime.Now.AddMinutes(60)); //cache duration: 60 mins
        } else {
            cache.Update(key, value, DateTime.Now.AddMinutes(60)); //cache duration: 60 mins
        }
        return;
    }
    /// <summary>
    /// Get value from cache
    /// </summary>
    /// <param name="key"></param>
    /// <returns>NULL if not in cache or time is exprired, otherwise, return cached value</returns>
    private object GetFromCache(string key) {
        SimpleMemoryCache cache;
        if (Application["SystemCache"] == null) {
            cache = new SimpleMemoryCache();
            Application["SystemCache"] = cache;
        } else {
            cache = (SimpleMemoryCache)Application["SystemCache"];
        }

        if (!cache.Contains(key)) {
            //not in cache or cache time is exprired
            return null;
        } else {
            return cache.Get(key);
        }
    }
    #endregion Cache controller
}
